package com.serkol.ams.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serkol.ams.bean.MyPage;
import com.serkol.ams.entity.*;
import com.serkol.ams.mapper.UsersWalletLogMapper;
import com.serkol.ams.modal.SqlFeildModal;
import com.serkol.ams.service.OrderMasterService;
import com.serkol.ams.service.UsersService;
import com.serkol.ams.service.UsersWalletLogService;
import com.serkol.annotation.RedisCache;
import com.serkol.constant.AuthConstant;
import com.serkol.handler.MyLambdaQueryWrapper;
import com.serkol.utils.DateFormat;
import com.serkol.utils.DateUtils;
import com.serkol.utils.ObjectUtils;
import com.serkol.wx.bean.TiChengMsg;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author pingan
 * @description 针对表【users_wallet_log】的数据库操作Service实现
 * @createDate 2022-09-27 12:06:15
 */
@Service
public class UsersWalletLogServiceImpl extends ServiceImpl<UsersWalletLogMapper, UsersWalletLog>
        implements UsersWalletLogService {
    @Autowired
    private OrderMasterService masterService;

    @Autowired
    private UsersService userService;
    @Override
    public MyPage<UsersWalletLog> findByMyList(int pageSize, int current, int state) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        QueryWrapper<UsersWalletLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UsersWalletLog::getUserId, loginLog.getUserId()).orderByDesc(UsersWalletLog::getCreateDate);
        if (state > 0) {
            queryWrapper.lambda().eq(UsersWalletLog::getState, state);
        }
        Page<UsersWalletLog> page = new Page<>(current, pageSize);
        IPage<UsersWalletLog> data = this.baseMapper.selectPage(page, queryWrapper);

        return MyPage.parsePage(data);
    }

    @Override
    //  @Cacheable(cacheNames = "findByBackLogList", key = "'findByBackLogList::userId'+#userId+'::state'+#state+'::pageSize'+#pageSize+'::currentPage'+#current",unless = "#current>0")
    public MyPage<Map<String, Object>> findByBackLogList(int pageSize, int current, int state, long userId) {

        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.authName(UsersWalletLog::getUserId).as("name").select(UsersWalletLog::getId,UsersWalletLog::getPrice, UsersWalletLog::getBalance, UsersWalletLog::getBalanceOld, UsersWalletLog::getRemark, UsersWalletLog::getCreateDate, UsersWalletLog::getType).attr("usersblancewithdrawaltype", UsersWalletLog::getState).as("stateName").authName(UsersWalletLog::getOperatorId).as("operatorName");
        queryWrapper.eq(UsersWalletLog::getUserId, userId).orderByDesc(UsersWalletLog::getCreateDate);
        if (state > 0) {
            queryWrapper.eq(UsersWalletLog::getState, state);
        }
        Page<Map<String, Object>> page = new Page<>(current, pageSize);
        IPage<Map<String, Object>> data = this.baseMapper.selectMapsPage(page, queryWrapper);

        return MyPage.parsePage(data);
    }

    @Override
    public MyPage<Map<String, Object>> findByPageLogList(int pageSize, int current, int state, String name, int type, long userId) {
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.authName(UsersWalletLog::getUserId).as("name").select(UsersWalletLog::getState,UsersWalletLog::getId, UsersWalletLog::getUserId, UsersWalletLog::getPrice, UsersWalletLog::getBalance, UsersWalletLog::getBalanceOld, UsersWalletLog::getRemark, UsersWalletLog::getCreateDate, UsersWalletLog::getType).attr("usersblancewithdrawaltype", UsersWalletLog::getState).as("stateName").authName(UsersWalletLog::getOperatorId).as("operatorName").authName(UsersWalletLog::getOrderUserId).as("orderUserName");
        queryWrapper.orderByDesc(UsersWalletLog::getId, UsersWalletLog::getCreateDate);
        if (state > 0) {
            queryWrapper.eq(UsersWalletLog::getState, state);
        }
        if (type > 0) {
            queryWrapper.eq(UsersWalletLog::getType, type);
        }
        if (userId > 0) {
            queryWrapper.eq(UsersWalletLog::getUserId, userId);
        }
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.inSql(UsersWalletLog::getUserId, SqlFeildModal.getAuthNameLike(name));
        }
        Page<Map<String, Object>> page = new Page<>(current, pageSize);
        IPage<Map<String, Object>> data = this.baseMapper.selectMapsPage(page, queryWrapper);

        return MyPage.parsePage(data);
    }


    @Override
    public Map<String, Object> myWalletLogStastica(Date startDate, Date endDate) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(UsersWalletLog::getState, 1).groupBy(UsersWalletLog::getUserId).dateBetween(UsersWalletLog::getCreateDate,DateFormat.DATE, startDate, endDate).eq(UsersWalletLog::getUserId, loginLog.getUserId());

        queryWrapper.select("COUNT(*) as  count,SUM(PRICE) price,(SELECT SUM(PRICE) FROM users_wallet_log where USER_ID=x.USER_ID AND STATE=1 LIMIT 1) priceAll");
        Map<String, Object> map = this.getMap(queryWrapper);
        if (map == null) {
            map = new HashMap<String, Object>();
            map.put("count", map.getOrDefault("count", 0));
            map.put("price", map.getOrDefault("price", 0.0));
            map.put("priceAll", map.getOrDefault("priceAll", 0.0));
        }

        return map;
    }

    @Override
    public Map<String, Object> teamWalletLogStastica(Date startDate, Date endDate) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        List<Long> findChildrens = userService.getFindChildrens(loginLog.getUserId());
        findChildrens.add(0L);

        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(UsersWalletLog::getState, 1).groupBy(UsersWalletLog::getUserId).dateBetween(UsersWalletLog::getCreateDate,DateFormat.DATE, startDate, endDate).in(UsersWalletLog::getUserId, findChildrens);

        queryWrapper.select("COUNT(*) as  count,SUM(PRICE) price");
        Map<String, Object> map = this.getMap(queryWrapper);
        if (map != null) {
            //IFNULL((SELECT SUM(PRICE) FROM users_wallet_log as tusers_wallet_log where USER_ID="+loginLog.getUserId()+" AND STATE=1 LIMIT 1),0) priceAll
            MyLambdaQueryWrapper<UsersWalletLog> queryWrapper1=new MyLambdaQueryWrapper<>();
            queryWrapper1.eq(UsersWalletLog::getState, 1).in(UsersWalletLog::getUserId, findChildrens);
            queryWrapper1.sum(UsersWalletLog::getPrice).as("priceAll");


            map = new HashMap<String, Object>();
            map.put("count", map.containsKey("count") ? map.get("count") : 0);
            map.put("price", map.containsKey("price") ? map.get("price") : 0.0);

            Map<String, Object> map1 = this.getMap(queryWrapper1);
            if(map1!=null){
                map.put("priceAll", map1.containsKey("priceAll") ? map1.get("priceAll") : 0.0);
            }

        }else {
            map=new HashMap<>();
            map.put("count", 0);
            map.put("price", 0.0);
            map.put("priceAll", 0.0);
        }

        return map;
    }

    @Override
    public Map<String, Object> myWalletStastica(long userId) {
//SUM(PRICE) as value,MONTH(CREATE_DATE) as timePeriod
        Date date = new Date();


        Map<String, Object> map = new HashMap<>();
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        queryWrapper.dateBetween(UsersWalletLog::getCreateDate, DateFormat.DATE_TIME, date, DateUtils.getDay(date, -7));
        List<BigDecimal> maps = this.listObjs(queryWrapper, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("weeks", maps);


        MyLambdaQueryWrapper<UsersWalletLog> queryWrapperWeekcount = new MyLambdaQueryWrapper<>();
        queryWrapperWeekcount.sum(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId).dateBetween(UsersWalletLog::getCreateDate, DateFormat.DATE_TIME, date, DateUtils.getDay(date, -7)).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        BigDecimal obj1Weeek = this.getObj(queryWrapperWeekcount, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("weekscount", ObjectUtils.bigDecimalNotNull(obj1Weeek));

        MyLambdaQueryWrapper<UsersWalletLog> queryWrapperall = new MyLambdaQueryWrapper<>();
        queryWrapperall.sum(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        BigDecimal obj = this.getObj(queryWrapperall, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("yearcountallyear", ObjectUtils.bigDecimalNotNull(obj));

        MyLambdaQueryWrapper<UsersWalletLog> queryWrapperallout = new MyLambdaQueryWrapper<>();
        queryWrapperallout.sum(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId).eq(UsersWalletLog::getState, 2).notIn(UsersWalletLog::getStatus, 2);
        BigDecimal objout = this.getObj(queryWrapperallout, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("yearcountallyearout", ObjectUtils.bigDecimalNotNull(objout));


        MyLambdaQueryWrapper<UsersWalletLog> queryWrapperallyear = new MyLambdaQueryWrapper<>();
        queryWrapperallyear.sum(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId).dateBetween(UsersWalletLog::getCreateDate, DateFormat.DATE_YEAR, date, DateUtils.getYear(date, -1)).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        BigDecimal obj1 = this.getObj(queryWrapperallyear, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("yearcountall", ObjectUtils.bigDecimalNotNull(obj1));


        MyLambdaQueryWrapper<UsersWalletLog> queryWrapperallyearout = new MyLambdaQueryWrapper<>();
        queryWrapperallyearout.sum(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId).dateBetween(UsersWalletLog::getCreateDate, DateFormat.DATE_YEAR, date, DateUtils.getYear(date, -1)).eq(UsersWalletLog::getState, 2).notIn(UsersWalletLog::getStatus, 2);
        BigDecimal obj1out = this.getObj(queryWrapperallyearout, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("yearcountallout", ObjectUtils.bigDecimalNotNull(obj1out));


        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper1 = new MyLambdaQueryWrapper<>();
        queryWrapper1.select(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId);
        queryWrapper1.dateBetween(UsersWalletLog::getCreateDate, DateFormat.DATE_MONTH, date, date).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        List<BigDecimal> maps1 = this.listObjs(queryWrapper1, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("month", maps1);


        MyLambdaQueryWrapper<UsersWalletLog> queryWrapperMontcount = new MyLambdaQueryWrapper<>();
        queryWrapperMontcount.sum(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId).dateBetween(UsersWalletLog::getCreateDate, DateFormat.DATE_MONTH, date, date).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        BigDecimal obj1Month = this.getObj(queryWrapperMontcount, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("monthcount", ObjectUtils.bigDecimalNotNull(obj1Month));


        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper3 = new MyLambdaQueryWrapper<>();
        queryWrapper3.select(UsersWalletLog::getPrice).eq(UsersWalletLog::getUserId, userId);
        queryWrapper3.dateBetween(UsersWalletLog::getCreateDate, DateFormat.DATE_YEAR, date, DateUtils.getYear(date, -1)).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        List<BigDecimal> maps3 = this.listObjs(queryWrapper3, (o) -> BigDecimal.valueOf(Double.valueOf(o.toString())));
        map.put("years", maps3);


        //SELECT SUM(PRICE),TYPE FROM users_wallet_log GROUP BY TYPE
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper4 = new MyLambdaQueryWrapper<>();
        queryWrapper4.attr("userswithdrawaltype", UsersWalletLog::getType).as("name").sum(UsersWalletLog::getPrice).as("value").groupBy(UsersWalletLog::getType).eq(UsersWalletLog::getUserId, userId).eq(UsersWalletLog::getState, 1).notIn(UsersWalletLog::getStatus, 2);
        List<Map<String, Object>> maps4 = this.listMaps(queryWrapper4);
        map.put("oval", maps4);
        return map;
    }

    @Override
    public Map<String, Object> myIncomeExpenses() {
        Map<String, Object> map = new HashMap<>();
        LoginLog loginLog = AuthConstant.getLoginLog();
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(UsersWalletLog::getState, 1).eq(UsersWalletLog::getUserId, loginLog.getUserId());
        queryWrapper.sum(UsersWalletLog::getPrice).as("price").month(UsersWalletLog::getCreateDate).as("mon");
        queryWrapper.last("GROUP BY mon");
        List<Map<String, Object>> maps = this.listMaps(queryWrapper);
        map.put("income", getInEx(maps));

        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper1 = new MyLambdaQueryWrapper<>();
        queryWrapper1.eq(UsersWalletLog::getState, 2).eq(UsersWalletLog::getUserId, loginLog.getUserId());
        queryWrapper1.sum(UsersWalletLog::getPrice).as("price").month(UsersWalletLog::getCreateDate).as("mon");
        queryWrapper1.last("GROUP BY mon");
        List<Map<String, Object>> maps1 = this.listMaps(queryWrapper1);
        map.put("export", getInEx(maps1));
        List<Integer> integerList = new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            integerList.add(i);
            //   System.out.println("getInEx" + i);
        }
        map.put("category", integerList);

        return map;
    }


    @Override
    public List<Map<String, Object>> myWalletStasticaOval() {
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper4 = new MyLambdaQueryWrapper<>();
        queryWrapper4.attr("userswithdrawaltype", UsersWalletLog::getType).as("name").sum(UsersWalletLog::getPrice).as("value").groupBy(UsersWalletLog::getType).notIn(UsersWalletLog::getStatus, 2);
        return this.listMaps(queryWrapper4);
    }

    @Override
    public List<Map<String, Object>> findByNotifyList(Long userId) {
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(UsersWalletLog::getPrice, UsersWalletLog::getType, UsersWalletLog::getState, UsersWalletLog::getRemark, UsersWalletLog::getStatus);
        queryWrapper.eq(UsersWalletLog::getUserId, userId).attr("userswithdrawaltype", UsersWalletLog::getType).as("typeName").select(UsersWalletLog::getCreateDate).as("createDate").orderByDesc(UsersWalletLog::getCreateDate);
        return this.listMaps(queryWrapper);
    }

   // @Cacheable(key = "'level::'+#state",value = "level:order::usersWalletLogService::log::findByLevelLogList")
    @Override
    public List<Map<String, Object>> findByLevelLogList(int state) {
        Date date = new Date();
      MyLambdaQueryWrapper<OrderMaster> queryWrapper = new MyLambdaQueryWrapper<>();
      queryWrapper.select(OrderMaster::getUserId).as("userId");

        queryWrapper.sum(OrderMaster::getPaymentAmount).as("price").groupBy(OrderMaster::getUserId).userAvatar(OrderMaster::getUserId).as("avatar").authLangName(OrderMaster::getUserId).as("name").orderByDesc(OrderMaster::getPaymentAmount).eq(OrderMaster::getStatus, 2).eq(OrderMaster::getIsPay, 1);
        queryWrapper.last("LIMIT 20");
        if (state == 1) {
            Date date1 = org.apache.commons.lang3.time.DateUtils.addMonths(date, -1);
            queryWrapper.dateBetween(OrderMaster::getCreateDate, DateFormat.DATE_TIME,date1, date);
        } else {
            Date date1 = org.apache.commons.lang3.time.DateUtils.addDays(date, -7);
            queryWrapper.dateBetween(OrderMaster::getCreateDate, DateFormat.DATE_TIME, date1, date);
        }
         List<Map<String, Object>> maps = masterService.listMaps(queryWrapper);

        List<Map<String, Object>> mapsList=new ArrayList<>();
        Iterator<Map<String, Object>> iterator = maps.iterator();
        while (iterator.hasNext()) {
            final Map<String, Object> next = iterator.next();
            Long userId1 =(Long) next.get("userId");
            Object allPrice = getAllPrice(userId1,state);
            next.put("priceAll",allPrice);
            mapsList.add(next);
        }
        return mapsList;
    }

    @Override
    public List<UsersWalletLog> findByMyMiniList(int state, int current) {
        int size = 10;
        int pagez = current * size;
        LoginLog loginLog = AuthConstant.getLoginLog();
        MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(UsersWalletLog::getId, UsersWalletLog::getPrice, UsersWalletLog::getState, UsersWalletLog::getType, UsersWalletLog::getRemark, UsersWalletLog::getStatus, UsersWalletLog::getCreateDate, UsersWalletLog::getOrderUserId);

        queryWrapper.eq(UsersWalletLog::getUserId, loginLog.getUserId()).orderByDesc(UsersWalletLog::getCreateDate);
        queryWrapper.select(SqlFeildModal.getAuthName("ORDER_USER_ID")).as("orderUserName");
        queryWrapper.last("LIMIT " + pagez + ",10");
        if (state > 0) {
            queryWrapper.eq(UsersWalletLog::getState, state);
        }

        return this.list(queryWrapper);
    }

    @Override
    public boolean withdrawalStatus(UsersWalletWithdrawal withdrawal) {

        LambdaUpdateWrapper<UsersWalletLog> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(UsersWalletLog::getBalance, withdrawal.getBalance()).eq(UsersWalletLog::getBalanceOld, withdrawal.getBalanceOld()).eq(UsersWalletLog::getType, withdrawal.getType()).eq(UsersWalletLog::getUserId, withdrawal.getUserId()).eq(UsersWalletLog::getStatus, 1).eq(UsersWalletLog::getPrice, withdrawal.getRequestAmount());
        queryWrapper.set(UsersWalletLog::getStatus, 2);

        return this.update(queryWrapper);
    }

    @Override
    public List<Map<String, Object>> financeChartStastic() {
        Date date = new Date();
   /*     MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
//dateFormat(UsersWalletLog::getCreateDate,DateFormat.DATE_MONTH).as("dateName")
        queryWrapper.sum(UsersWalletLog::getPrice).as("price").dateFormat(UsersWalletLog::getCreateDate, DateFormat.DATE_MONTH).as("name").notIn(UsersWalletLog::getStatus, 2).
                eq(UsersWalletLog::getState, 1);
        queryWrapper.last(" GROUP BY name ORDER BY price DESC");*/
        QueryWrapper<UsersWalletLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getFinanceStatastica());
//WHERE (status NOT IN (2) AND state = 1) GROUP BY name ORDER BY price DESC LIMIT 20
        queryWrapper.lambda().notIn(UsersWalletLog::getStatus,2).eq(UsersWalletLog::getState,1);
        queryWrapper.groupBy("ym").orderByDesc("name");

        return listMaps(queryWrapper);
    }

    @RedisCache(key = "wsersWalletLogService::log::findByPerList", isParam = true,time = 5)
    @Override
    public List<Map<String, Object>> findByPerList(long userId) {
        List<Long> findChildrens =null;
        if(userId>0){
            findChildrens=userService.getFindChildrens(userId);
        }else {
            LoginLog loginLog = AuthConstant.getLoginLog();
              userId = loginLog.getUserId();
            findChildrens=userService.getFindChildrens(userId);
        }
        findChildrens.add(0L);
    //  findChildrens.add(userId);
        List<String> collect = findChildrens.stream().map(o -> {
            return String.valueOf(o);
        }).collect(Collectors.toList());
       // String join = String.join(",", collect);
        MyLambdaQueryWrapper<OrderMaster> queryWrapper=new MyLambdaQueryWrapper<>();
        queryWrapper.sum(OrderMaster::getPaymentAmount).as("price").select("DATE_FORMAT(CREATE_DATE,'%Y-%m')").as("date")
                .last(true,"GROUP BY DATE_FORMAT(CREATE_DATE,'%Y-%m') ORDER BY create_date DESC ")
                .eq(OrderMaster::getIsPay,1)
                .in(OrderMaster::getUserId,collect);
         List<Map<String, Object>> maps = masterService.listMaps(queryWrapper);

        return maps;
    }
  //  @RedisCache(key = "wsersWalletLogService::log::findByPerUsersList", isParam = true)
 //@Cacheable(key = "'statstic::'+#replace+'::userId'+#userId",value = "usersWalletLogService::log::findByPerUsersList",condition = "#sameMonth==false")
    @Override
    public List<Map<String, Object>> findByPerUsersList(long userId, String date, boolean sameMonth, String replace) {
        System.out.println("replace:"+replace);




        MyLambdaQueryWrapper<Users> queryWrapper=new MyLambdaQueryWrapper<>();
        String fs="";
      if(StringUtils.isNotEmpty(date)) {
            Date sdate = DateUtil.parse(date+"-01");
        String  fs1 = DateUtil.format(sdate,"yyyy-MM");
        fs="AND (date_format(CREATE_DATE,'%Y-%m') ='" + fs1 + "')";
           // queryWrapper.dateEq(OrderMaster::getCreateDate, DateFormat.DATE_MONTH, sdate);

        }
        queryWrapper.select("(SELECT IFNULL(SUM(PAYMENT_AMOUNT),0) FROM order_master as torder_master WHERE IS_PAY=1 AND STATUS=2 AND USER_ID=x.ID  "+fs+" )").as("price")
               // .eq(OrderMaster::getStatus,2).eq(OrderMaster::getIsPay,1)
                .select(Users::getAvatar).as("avatar")
                .authName(Users::getId).as("name")
                .select(Users::getPhone).as("phone")
                .select(Users::getId).as("userId")
                .eq(Users::getParentUserId,userId);
        List<Map<String, Object>> maps = userService.listMaps(queryWrapper);

        List<Map<String, Object>> mapsList=new ArrayList<>();
         Iterator<Map<String, Object>> iterator = maps.iterator();
        while (iterator.hasNext()) {
            final Map<String, Object> next = iterator.next();
             Long userId1 =(Long) next.get("userId");
             Object allPrice = getAllPrice(userId1,date);
            next.put("priceAll",allPrice);
            mapsList.add(next);
        }
        return mapsList;
    }
    @Cacheable(key = "'statstic::my::'+#replace+'::userId'+#userId",value = "usersWalletLogService::log::findByPerUser",condition = "#sameMonth==false")
    @Override
    public Map<String, Object> findByPerUser(long userId, String date, boolean sameMonth, String replace) {
        System.out.println("replace:"+replace);


        List<Long> findChildrens =null;
        if(userId>0){
            findChildrens=userService.getFindChildrens(userId);
        }else {
            LoginLog loginLog = AuthConstant.getLoginLog();
            userId = loginLog.getUserId();
            findChildrens=userService.getFindChildrens(userId);
        }
        findChildrens.add(0L);

        List<String> collect = findChildrens.stream().map(o -> {
            System.out.println("-------------------------------------");
            System.out.println(o);
            return String.valueOf(o);
        }).collect(Collectors.toList());

        MyLambdaQueryWrapper<OrderMaster> queryWrapper=new MyLambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(date)) {
            Date sdate = DateUtil.parse(date+"-01");
            queryWrapper.dateEq(OrderMaster::getCreateDate, DateFormat.DATE_MONTH, sdate);
        }
        queryWrapper.sum(OrderMaster::getPaymentAmount).as("price")
                .eq(OrderMaster::getStatus,2).eq(OrderMaster::getIsPay,1)
          .orderByDesc(OrderMaster::getPaymentAmount).eq(OrderMaster::getUserId,userId)
               .last("LIMIT 1");
        Map<String, Object> map = masterService.getMap(queryWrapper);
if(map==null) {
    map=new HashMap<>();
    map.put("price",0);
}

    Object allPrice = getAllPrice(userId, date);
    map.put("priceAll", allPrice);
    map.put("count",collect.size());


        return map;
    }

    @Override
    public List<TiChengMsg> getWxMsgs(Long orderId) {
        try {
            MyLambdaQueryWrapper<UsersWalletLog> queryWrapper = new MyLambdaQueryWrapper<>();
            queryWrapper.eq(UsersWalletLog::getOrderId, orderId).eq(UsersWalletLog::getState, 1);
            queryWrapper.authName(UsersWalletLog::getUserId).as("thing4")
                    .select("IFNULL((SELECT MP_OPENID FROM users WHERE ID=USER_ID LIMIT 1),'')").as("openId")
                    .select(UsersWalletLog::getPrice).as("thing5")
                    .authName(UsersWalletLog::getOrderUserId).as("thing3");

            Stream<TiChengMsg> tiChengMsgStream = listMaps(queryWrapper).stream().map(o -> {
                TiChengMsg tiChengMsg = new TiChengMsg();
                tiChengMsg.setThing3(o.get("thing3").toString());
                tiChengMsg.setThing4(o.get("thing4").toString());
                tiChengMsg.setThing5(o.get("thing5").toString());
                tiChengMsg.setOpenId(o.get("openId").toString());
                return tiChengMsg;
            });
            return tiChengMsgStream.collect(Collectors.toList());
        } catch (Exception e) {
            // 记录日志或处理异常
            e.printStackTrace();
            return List.of();
        }
    }

    private  Object getAllPrice(long userId, String date){
        List<Long> findChildrens =null;
        if(userId>0){
            findChildrens=userService.getFindChildrens(userId);
        }else {

            findChildrens=new ArrayList<>();
        }
        findChildrens.add(0L);
        //   findChildrens.add(userId);

        List<String> collect = findChildrens.stream().map(o -> {
            return String.valueOf(o);
        }).collect(Collectors.toList());
        // String join = String.join(",", collect);

        MyLambdaQueryWrapper<OrderMaster> queryWrapper=new MyLambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(date)) {
            Date sdate = DateUtil.parse(date+"-01");
            queryWrapper.dateEq(OrderMaster::getCreateDate, DateFormat.DATE_MONTH, sdate);
        }
        queryWrapper.sum(OrderMaster::getPaymentAmount).as("price")
                .eq(OrderMaster::getStatus,2).eq(OrderMaster::getIsPay,1)
                .in(OrderMaster::getUserId,collect);
         Map<String, Object> map = masterService.getMap(queryWrapper);
        Object result;
        if (map!=null) {
            result=map.get("price");
        }else {
            result=0;
        }
        return  result;
    };

    private  Object getAllPrice(long userId, int state){
        Date date=new Date();
        List<Long> findChildrens =null;
        if(userId>0){
            findChildrens=userService.getFindChildrens(userId);
        }else {

            findChildrens=new ArrayList<>();
        }
        findChildrens.add(0L);
        //   findChildrens.add(userId);

        List<String> collect = findChildrens.stream().map(o -> {
            return String.valueOf(o);
        }).collect(Collectors.toList());
        // String join = String.join(",", collect);

        MyLambdaQueryWrapper<OrderMaster> queryWrapper=new MyLambdaQueryWrapper<>();
        if (state == 1) {
            Date date1 = org.apache.commons.lang3.time.DateUtils.addMonths(date, -1);
            queryWrapper.dateBetween(OrderMaster::getCreateDate, DateFormat.DATE_TIME,date1, date);
        } else {
            Date date1 = org.apache.commons.lang3.time.DateUtils.addDays(date, -7);
            queryWrapper.dateBetween(OrderMaster::getCreateDate, DateFormat.DATE_TIME, date1, date);
        }
        queryWrapper.sum(OrderMaster::getPaymentAmount).as("price")
                .eq(OrderMaster::getStatus,2).eq(OrderMaster::getIsPay,1)
                .in(OrderMaster::getUserId,collect);
        Map<String, Object> map = masterService.getMap(queryWrapper);
        Object result;
        if (map!=null) {
            result=map.get("price");
        }else {
            result=0;
        }
        return  result;
    };


    private Collection<Object> getInEx(List<Map<String, Object>> maps) {
        Map<Integer, Object> map = new HashMap<>();

        for (Map<String, Object> next : maps) {
            map.put(Integer.valueOf(next.get("mon").toString()), next.get("price"));
        }
        for (int i = 1; i < 13; i++) {
            if (!map.containsKey(i)) {
                map.put(i, 0);
            }
            //   System.out.println("getInEx" + i);
        }

//        Map<String, Object> map1 = new HashMap<>();
//        map1.put("category", map.keySet());
//        map1.put("data", map.values());
        return map.values();
    }

}




